package com.sky.controller.admin;

import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@Api(tags = "菜品管理")
@RequestMapping("/admin/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    //新增菜品
    @ApiOperation("新增菜品")
    @PostMapping
    public Result save(@RequestBody DishDTO dishDTO){
        //进行添加菜品
        log.info("新增菜品:{}",dishDTO);
        dishService.save(dishDTO);
        //新增完菜品之后应该清除这个分类菜品的缓存
        String key = "dish_" + dishDTO.getCategoryId();
        redisTemplate.delete(key);
        return Result.success();
    }
    //条件分页查询
    @ApiOperation("菜品分页查询")
    @GetMapping("/page")
    public Result<PageResult> queryByPage(DishPageQueryDTO dishPageQueryDTO){
        PageResult pageResult = dishService.queryByPage(dishPageQueryDTO);
        return Result.success(pageResult);
    }
    //批量删除菜品
    @ApiOperation("批量删除菜品")
    @DeleteMapping
    public Result deleteByIds(@RequestParam List<Long> ids){
        dishService.deleteByIds(ids);
        clearDishCache();
        return Result.success();
    }
    //根据Id查询菜品信息
    @ApiOperation("根据Id查询菜品信息")
    @GetMapping("/{id}")
    public Result<DishVO> queryById(@PathVariable Long id) {
        DishVO dishVO = dishService.queryByIdWithFlavor(id);
        return  Result.success(dishVO);
    }
    //根据id修改菜品信息
    @PutMapping
    @ApiOperation("根据id修改菜品信息")
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品:{}",dishDTO);
        dishService.updateById(dishDTO);
        clearDishCache();
        return Result.success();
    }
    //起售和停售菜品
    @PostMapping("/status/{status}")
    @ApiOperation("菜品起售和停售")
    public Result startOrStop(@PathVariable Integer status,Long id){
        dishService.startOrStop(status,id);
        clearDishCache();
        return Result.success();
    }
    //根据分类ID查询菜品信息
    @ApiOperation("根据分类id查询菜品")
    @GetMapping("/list")
    public Result<List<Dish>> queryByCategoryId(Long categoryId){
        List<Dish> dishList = dishService.queryByCategoryId(categoryId);
        return Result.success(dishList);
    }

    //清除菜品的全部的缓存
    public void clearDishCache(){
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }
}
